package abc.base;

import abc.model.IEntity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.enums.SqlMethod;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import lombok.Data;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.session.Configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;

import java.io.Serializable;

@Data
@Component
public abstract class BaseModel<E extends Model<?>> extends Model<E> implements Serializable {
    @TableId(type = IdType.ASSIGN_ID)
    @TableField(value = "id")
    @JsonSerialize(using = ToStringSerializer.class)
    protected Long id;

    private final transient Class<?> entityClass = this.getClass();

    public static <T extends Model<?>> BaseModel<T> build(Class<T> clazz) throws Exception {
        return (BaseModel<T>) ReflectionUtils.accessibleConstructor(clazz).newInstance();
    }

    public Configuration getConfiguration() {
        return super.sqlSession().getConfiguration();
    }

    public MappedStatement getMappedStatement(SqlMethod method) {
        return super.sqlSession().getConfiguration().getMappedStatement(super.sqlStatement(method));
    }

    public QueryWrapper<E> where() {
        return new QueryWrapper<E>();
    }

    public abstract <T extends IEntity<?>> T toVo();

    @Override
    public Serializable pkVal() {
        return id;
    }
}
